﻿using Autofac.Core;
using Autofac.Core.Registration;
using AutoRegistDependency.Component;
using AutoRegistDependency.Interface;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoRegistDependency.Attributes.Condition
{
    /// <summary>
    /// 当容器内存在指定的组件时，才会注册此组件
    /// This component is only registered when the specified component exists within the container
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public sealed class ConditionalOnBeanAttribute : Attribute, ICondition
    {
        /// <summary>
        /// 组件的key
        /// </summary>
        public object Key { get;set; }
        /// <summary>
        /// 指定bean的类型
        /// </summary>
        public Type ComponentType { get;set; }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="componentType">指定bean的类型</param>
        public ConditionalOnBeanAttribute(Type componentType)
        {
            ComponentType = componentType;
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="key">指定组件的key</param>
        /// <param name="componentType">指定bean的类型</param>
        public ConditionalOnBeanAttribute(object key, Type componentType)
        {
            Key = key;
            ComponentType = componentType;
        }

        public bool Matches(HostBuilderContext hostBuilderContext, IComponentRegistryBuilder componentRegistry, ComponentDefinition component)
        {
            Service service;
            if(Key!=null)
            {
                service = new KeyedService(Key, ComponentType); 
            }
            else
            {
                service = new TypedService(ComponentType);
            }
            return componentRegistry.IsRegistered(service);
        }
    }
}
